// 基于准备好的dom，初始化echarts实例
var myChart = echarts.init(document.getElementById('echarts'));

function splitData(rawData) {
	var categoryData = [];
	var values = [];
	var volumns = [];
	for(var i = 0; i < rawData.length; i++) {
		categoryData.push(rawData[i].splice(0, 1)[0]);
		values.push(rawData[i]);
		volumns.push(rawData[i][4]);
	}
	return {
		categoryData: categoryData,
		values: values,
		volumns: volumns
	};
}

function calculateMA(dayCount, data) {
	var result = [];
	for(var i = 0, len = data.values.length; i < len; i++) {
		if(i < dayCount) {
			result.push('-');
			continue;
		}
		var sum = 0;
		for(var j = 0; j < dayCount; j++) {
			sum += data.values[i - j][1];
		}
		result.push(+(sum / dayCount).toFixed(3));
	}
	return result;
}

$.get('stock_DJI.json', function(rawData) {
	var data = splitData(rawData);
	myChart.setOption(option = {
		backgroundColor: '#eee',
		animation: false,
		legend: {
			bottom: 10,
			left: 'center',
			data: ['Dow-Jones index', 'MA5', 'MA10', 'MA20', 'MA30']
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'line'
			}
		},
		toolbox: {
			feature: {
				dataZoom: {
					yAxisIndex: false
				},
				brush: {
					type: ['lineX', 'clear']
				}
			}
		},
		brush: {
			xAxisIndex: 'all',
			brushLink: 'all',
			outOfBrush: {
				colorAlpha: 0.1
			}
		},
		grid: [{
			left: '10%',
			right: '8%',
			height: '50%'
		}, {
			left: '10%',
			right: '8%',
			top: '63%',
			height: '16%'
		}],
		xAxis: [{
			type: 'category',
			data: data.categoryData,
			scale: true,
			boundaryGap: false,
			axisLine: {
				onZero: false
			},
			splitLine: {
				show: false
			},
			splitNumber: 20,
			min: 'dataMin',
			max: 'dataMax'
		}, {
			type: 'category',
			gridIndex: 1,
			data: data.categoryData,
			scale: true,
			boundaryGap: false,
			axisLine: {
				onZero: false
			},
			axisTick: {
				show: false
			},
			splitLine: {
				show: false
			},
			axisLabel: {
				show: false
			},
			splitNumber: 20,
			min: 'dataMin',
			max: 'dataMax'
		}],
		yAxis: [{
			scale: true,
			splitArea: {
				show: true
			}
		}, {
			scale: true,
			gridIndex: 1,
			splitNumber: 2,
			axisLabel: {
				show: false
			},
			axisLine: {
				show: false
			},
			axisTick: {
				show: false
			},
			splitLine: {
				show: false
			}
		}],
		dataZoom: [{
			type: 'inside',
			xAxisIndex: [0, 1],
			start: 98,
			end: 100
		}, {
			show: true,
			xAxisIndex: [0, 1],
			type: 'slider',
			top: '85%',
			start: 98,
			end: 100
		}],
		series: [{
			name: 'MA5',
			type: 'line',
			data: calculateMA(5, data),
			smooth: true,
			lineStyle: {
				normal: {
					opacity: 0.5
				}
			}
		}, {
			name: 'MA10',
			type: 'line',
			data: calculateMA(10, data),
			smooth: true,
			lineStyle: {
				normal: {
					opacity: 0.5
				}
			}
		}]
	}, true);

	myChart.dispatchAction({
		type: 'brush',
		areas: [{
			brushType: 'lineX',
			coordRange: ['2016-06-02', '2016-06-20'],
			xAxisIndex: 0
		}]
	});
});